package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
@Autowired
private EmpExprService empExprService;
    @Override
    public void empSave(Emp emp) {

        //补全数据
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        this.save(emp);
        //添加工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList!=null&&exprList.size()>0){
            exprList.forEach(e->e.setEmpId(emp.getId()));
            empExprService.saveBatch(exprList);
        }


    }

    @Override
    public Emp getByIdEmp(Integer id)  {
        Emp byId = this.getById(id);
        if (byId==null){
            throw new RuntimeException("数据不存在");
        }
        //查询工作经历
        //select * from emp_exer where emp_id=?
        List<EmpExpr> list = empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, byId.getId()));
        byId.setExprList(list);
        return byId;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void empUpdate(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);

        //通过条件 select * from emp_exer where emp_id=?
        LambdaQueryWrapper<EmpExpr> eq = new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId());
        //删除原有的
        empExprService.remove(eq);
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList!=null&&exprList.size()>0){

            empExprService.saveBatch(exprList);
            //haochen
        }
    }

    @Override
    public void deleteEmp(List<Integer> ids) {
        this.removeByIds(ids);
        empExprService.remove( new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, ids));


    }
}
